const axios = require('axios');
const db = require("../db/mysql");

const getIpData = async (ctx) => {
    try {
        // 获取IP（处理代理情况）
        const ip = ctx.request.headers['x-forwarded-for'] || ctx.request.ip;
        // const ip ='222.210.208.247';
        // 调用IP-API获取地理信息
        const response = await axios.get(`http://ip-api.com/json/${ip}`);
        const ipData = response.data;
        console.log(ipData);
        // 如果API返回失败
        if (ipData.status !== 'success') {
            ctx.body = {
                code: 500,
                message: 'IP查询失败: ' + (ipData.message || '未知错误'),
                data: null
            };
            return;
        }
        // 插入数据库（使用参数化查询防止SQL注入）
        const insertSql = `
            INSERT INTO log_visit_blfx 
            (ip, country, city, lon, lat, logtime) 
            VALUES (?, ?, ?, ?, ?, NOW())
        `;
        const params = [
            ipData.query,       // IP
            ipData.country,     // 国家
            ipData.city,        // 城市
            ipData.lon,         // 经度
            ipData.lat          // 纬度
        ];
        // 返回结构化数据
        ctx.body = {
            code: 200,
            message: 'success',
            data: {
                ip: ipData.query,
                location: {
                    country: ipData.country,
                    region: ipData.regionName,
                    city: ipData.city,
                    coordinates: [ipData.lon, ipData.lat]
                },
                network: {
                    isp: ipData.isp,
                    as: ipData.as
                }
            }
        };
        // 执行SQL（假设你的db模块支持Promise）
        await db.query(insertSql, params);

    } catch (err) {
        console.error('IP记录错误:', err);
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: '服务器内部错误',
            data: null
        };
    }
};
const healthCheck = async (ctx) => {
    ctx.body = { code: 200, message: 'get请求访问正常', data: 'Hello Koa!' + ctx.request.ip };
}
const healthCheckPost = async (ctx) => {
    ctx.body = { code: 200, message: 'post请求访问正常', data: 'Hello Koa!' + ctx.request.ip };
}
module.exports = { getIpData, healthCheck, healthCheckPost };
